package com.devplatform.config;

import com.devplatform.interceptor.TokenInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
    //白名单
    private final List<String> whitelist = List.of(
            "/api/user/getToken",
            "/api/user/register",
            "/api/user/resetPassword",
            "/api/user/getHomeInfo",
            "/api/captcha",
            "/api/email/getEmailCode",
            "/api/article/getList",
            "/api/article/getCategoryList",
            "/api/article/getCategories",
            "/api/article/getHotList",
            "/api/article/getDetail",
            "/api/comments/getComments/*",
            "/api/ads/homeAds",
            "/api/ads/loggedAds",
            "/api/ads/recordImpression"
    );

    private final TokenInterceptor tokenInterceptor;

    //配置跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 允许所有路径的请求
        registry.addMapping("/**")
                // 允许所有来源的请求
                .allowedOriginPatterns("*")
                // 允许所有HTTP方法（GET, POST, PUT, DELETE等）
                .allowedMethods("*")
                // 允许携带凭证（如 Cookie, Authorization Header）
                .allowCredentials(true)
                // 设置预检请求（Pre-flight request）的缓存时间，单位为秒
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册拦截器
        registry.addInterceptor(tokenInterceptor)
                //定义需要拦截的请求路径
                .addPathPatterns("/api/**")
                //定义需要排除的白名单
                .excludePathPatterns(whitelist);
    }
}
